package com.ruoyi.common.websocket;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.ruoyi.common.constant.CacheConstants.LOGIN_TOKEN_KEY;

@Slf4j
public class WebsocketFilter implements Filter {
    private static final String TOKEN_KEY = "Sec-WebSocket-Protocol";

    private static RedisCache redisCache;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (redisCache == null) {
            redisCache = SpringUtils.getBean(RedisCache.class);
        }
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader(TOKEN_KEY);

        log.debug("Websocket连接 Token安全校验，Path = {}，token:{}", request.getRequestURI(), token);

        if (token.contains(LOGIN_TOKEN_KEY)) { // 小程序的情况
            RedisCache redisCache = SpringUtils.getBean("redisCache");
            if (!redisCache.hasKey(token)) {
                return;
            }
        }

        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader(TOKEN_KEY, token);
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
